#!/bin/bash
# why:set cpu c state to C0 . usage sh <sc name> 0
function PrintUsage()
{
 echo "$0 [0 | 1]"
 echo "$0 [0 | 1] min_cpu max_cpu"
 echo "    0 = set to C0 only"
 echo "    1 = set to max configured C state"
 echo "    the min/max cpu number is inclusive"
 exit 1
}

if [ $# != 1 -a $# != 3 ]; then
 PrintUsage
fi

case $1 in
 0|1)
  ;;
 *)
  PrintUsage
  ;;
esac

if [ $# -gt 1 ]; then
 case $2 in
  *[!0-9]*)
   PrintUsage
   ;;
  *)
   ;;
    esac

 case $3 in
  *[!0-9]*)
   PrintUsage
   ;;
  *)
   ;;
 esac

 if [ $2 -gt $3 ]; then
  PrintUsage
 fi
fi

cd /sys/devices/system/cpu/cpuidle || exit 0

NUMSTATE="`ls | wc -w`"
cd /sys/devices/system/cpu
NUMCPUS="`ls -d cpu[0-9] cpu[0-9][0-9] cpu[0-9][0-9][0-9] 2> /dev/null | wc -w`"

CPUMIN=0
CPUMAX=$NUMCPUS

if [ $# -gt 1 ]; then
 if [ $2 -ge $CPUMAX -o $3 -ge $CPUMAX ]; then
  PrintUsage
 fi

 CPUMIN=$2
 CPUMAX=$(($3 + 1))
fi

echo "Min:$CPUMIN - Max:$((CPUMAX-1))"

for((ii=CPUMIN;ii<CPUMAX;ii++)); do
 cd /sys/devices/system/cpu/cpu$ii/cpuidle 2> /dev/null || continue
 if [ $1 = 0 ]; then
  for((ij=NUMSTATE-1;ij>=0;ij--)); do
   echo 1 > state$ij/disable
  done
 else
  for((ij=0;ij<NUMSTATE;ij++)); do
   echo 0 > state$ij/disable
  done
 fi
done